import { appStore } from '@renderer/store/modules/app'
import { Modal } from 'ant-design-vue'
import { onUnmounted } from 'vue'

// Move事件
const MOVE_ENVENT_KEYS = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']

const convertEventKey = (key: string) => {
  const reg = /Arrow(.*)$/
  return key.match(reg)[1].toLowerCase()
}

export const useKeyboard = () => {
  const listener = (e: KeyboardEvent) => {
    const {
      isGameStart,
      initGame,
      handleMove,
      handleBack,
      handleEnd
    } = appStore
    const key = e.key
    // 处理游戏开始事件
    if (key === 'g') {
      initGame()
    }
    // 游戏未开始时不处理键盘事件
    if (!isGameStart) return
    // 处理Move事件
    if (MOVE_ENVENT_KEYS.indexOf(key) >= 0) {
      handleMove(convertEventKey(key))
      return
    }
    // 处理游戏结束事件
    if (key === 'e') {
      Modal.confirm({
        title: '系统提示',
        content: `游戏得分为 ${appStore.gameScore}, 确定要结束?`,
        onOk () {
          handleEnd()
        }
      })
      return
    }
    // 处理返回事件
    if (key === 'b') {
      handleBack()
    }
  }
  window.addEventListener('keyup', listener, true)
  // 注销监听事件
  onUnmounted(() => {
    window.removeEventListener('keyup', listener, true)
  })
}
